<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <script>
      var obj = {
        str: 'shu',
        num: 123
      };
      function render() {
        console.log('数据变化了，该重新渲染到页面了');
      }
      //  定义一个观察者
      function observer(obj) {
        if (typeof obj !== 'object' || obj == null) {
          return obj;
        }
        for (let attr in obj) {
          console.log(attr);
          dr(obj,attr, obj[attr]);
        }
      }
      observer(obj);

      function dr(data, key, value) {
        Object.defineProperty(data, key, {
          get() {
            //获取属性时执行
            return value;
          },
          set(newVal) {
            //监听到属性值发生变化到时候执行
            render();
            value = newVal;
          }
        });
      }
      obj.str = 'hao';
      console.log(obj.str);
    </script>
  </body>
</html>
